function [ap,resVol,hRes,qDownstreamRel] = resS(resVolIni,cp,op,tEnd,aSH,bSH,hMin,hMax,mult)
%
% Idea: if excess flow, fill reservoir, otherwise water fields. Priority
% lies in covering immediate demand as good as possible. Use simple storage
% height relationship
%
% v 0.2, Tobias Siegfried, 03042007 

% Initalize
resVol = zeros(1,tEnd);
resVol(1) = resVolIni;
hRes = zeros(1,tEnd);
ap = zeros(1,tEnd);
qDownstreamRel = ap;
fluxConv = 24*3600;
% Main
for t= 1 : tEnd
    if cp(t) > op(t) % Fill that reservoir
        resIn = cp(t)-op(t);
        resVol(t+1) = resVol(t) + resIn*fluxConv;
        hRes(t+1) = (resVol(t+1)/aSH)^(1/bSH);
        ap(t) = op(t); % optimal performance
        if ap(t)>op(t), keyboard, end
    else % Consume if enough water is available
        if hRes(t) > hMin
            dem = op(t) - cp(t);
            % Check reservoir level
            testH = ((resVol(t)-dem*fluxConv)/aSH)^(1/bSH);
            if testH > hMin
                ap(t) = op(t);
                resVol(t+1) = resVol(t) - dem*fluxConv;
                hRes(t+1) = (resVol(t+1)/aSH)^(1/bSH);
                if ap(t)>op(t), keyboard, end
            else % Consume as much as you can from the reservoir.
                relRes = -aSH*hMin^bSH+resVol(t);
                ap(t) = relRes/fluxConv;
                resVol(t+1) = resVol(t) - relRes;
                hRes(t+1) = (resVol(t+1)/aSH)^(1/bSH);
                if ap(t)>op(t), keyboard, end
            end
        else % Consuming is not possible because reservoir level below dead storage
            ap(t) = op(t)-cp(t);
            resVol(t+1) = resVol(t);
            hRes(t+1) = (resVol(t+1)/aSH)^(1/bSH);
            if ap(t)>op(t), keyboard, end
        end
    end
    % Get rid of excess storage by checking max. storage volume
    if hRes(t+1) > hMax
        qDownstreamRel(t+1) = (aSH*(hRes(t+1)-hMax)^bSH)/fluxConv;
        hRes(t+1) = hMax;
        resVol(t+1) = aSH*hRes(t+1)^bSH;
    else
        qDownstreamRel(t+1) = 0;
    end
end
keyboard